package com.ex3;

import java.util.concurrent.Semaphore;

public class MessageQueue {

    private Semaphore emptySlots; // 表示可用空间数量
    private Semaphore fullSlots;  // 表示消息数量

    private String[] buffer;  // 缓冲区
    private int size;         // 缓冲区大小

    public MessageQueue(int bufferSize) {
        this.size = bufferSize;
        this.emptySlots = new Semaphore(size);
        this.fullSlots = new Semaphore(0);
        this.buffer = new String[size];  // 初始化缓冲区
    }

    // 将消息放入队列中
    public void putMessage(String message) throws InterruptedException {
        emptySlots.acquire();  // 等待可用空间
        synchronized (this) {
            // 放入消息到缓冲区
            int index = getIndex();
            buffer[index] = message;
        }
        fullSlots.release();  // 通知消息数量增加
    }

    // 从队列中取出消息
    public String takeMessage() throws InterruptedException {
        fullSlots.acquire();  // 等待消息数量
        String message;
        synchronized (this) {
            // 从缓冲区取出消息
            int index = getIndex();
            message = buffer[index];
            buffer[index] = null;  // 清空缓冲区
        }
        emptySlots.release();  // 通知可用空间增加
        return message;
    }

    // 判断队列是否为空
    public boolean isEmpty() {
        return fullSlots.availablePermits() == 0;
    }

    // 获取队列大小
    public int size() {
        return fullSlots.availablePermits();
    }

    // 获取缓冲区索引
    private int getIndex() {
        return (size - emptySlots.availablePermits() - 1) % size;
    }
}